package org.hanbo.code.repository.persistence.entity;

import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import org.hanbo.code.repository.persistence.DAOBase;

import com.google.appengine.api.datastore.Key;

public class RegisteredUserDAO	extends DAOBase
{
	public RegisteredUserDAO()
	{ }
	
	public Key persistRegisteredUser(RegisteredUser userToPersist)
	{
		if (userToPersist != null && userToPersist.isUserInfoValid())
		{
			//System.out.println("Before registering ... valid");

			String userName = userToPersist.getUserName();
			if (!isUserRegistered(userName))
			{
				//System.out.println("User appeared not registered");
				if(super.isPersistenceManagerAcquired())
				{
					RegisteredUser userPersistent = super
						.getPersistenceManager()
						.<RegisteredUser>makePersistent(userToPersist);
					//System.out.println("User registration persisted");
					return userPersistent.getUserId();
				}
			}
		}
		
		throw new IllegalArgumentException("Input parameter userToPersist. User [" + userToPersist.getUserName() + "] has been registered");
	}
	
	public RegisteredUser getRegisteredUserById(Key userId)
	{
		if (userId == null)
		{
			throw new IllegalArgumentException("Invalid parameter: userId");
		}
		if(!super.isPersistenceManagerAcquired())
		{
			throw new IllegalArgumentException("Invalid persistene manager for getRegisteredUserById.");
		}
		
		RegisteredUser userPersistent = super.getPersistenceManager()
			.getObjectById(RegisteredUser.class, userId);
		return userPersistent;
	}
	
	public RegisteredUser getRegisteredUserByEmail(String userEmail)
	{
		if (userEmail == null || userEmail.length() <= 0)
		{
			throw new IllegalArgumentException("Invalid parameter: userEmail");			
		}
		if(!super.isPersistenceManagerAcquired())
		{
			throw new IllegalArgumentException("Invalid persistene manager for getRegisteredUserByEmail.");
		}
		
		Query query = null;
		PersistenceManager pm = super.getPersistenceManager();
		query = pm.newQuery(RegisteredUser.class);
		query.setFilter("userName == userNameParam");
		query.declareParameters("String userNameParam");

		//System.out.println("Atempt to find user - " + userEmail);

		@SuppressWarnings("unchecked")
		List<RegisteredUser> results = (List<RegisteredUser>) query.execute(userEmail);
		if (results.size() == 0)
		{
			//System.out.println("Return result set, size 0, find failed...");
			return null;
		}
		else if (results.size() == 1)
		{
			//System.out.println("Return result set, size 1, find succeeded.");
			return results.get(0);
		}
		
		throw new RuntimeException("More than 1 user shared the same email.");
	}
	
	public boolean isUserRegistered(String userEmail)
	{
		RegisteredUser user = getRegisteredUserByEmail(userEmail);
//		if (user != null)
//		{
//			System.out.println("isUserRegistered: " + user.getUserId().getId());
//		}
		return (user != null);
	}
}
